<template>
    <el-drawer v-model="props.drawer" title="列设置（可拖动排序）" direction="rtl" :before-close="handleCloseChange"  size="50%"
        @handleClose="handleCloseChange" :close-on-press-escape="false">
        <div class="column-drawer-box">
            <div class="column-drawer-box-content">
                <el-table :data="columnData" style="width: 100%" height="100%" border ref="elTableRef" stripe row-key="prop">
                    <el-table-column type="index" width="60" label="序号" align="center" />
                    <el-table-column label="列名称" prop="title" align="center"></el-table-column>
                    <el-table-column label="字段名" prop="prop" align="center"></el-table-column>
                    <el-table-column label="是否显示列" prop="showColumn" align="center" width="100">
                        <template #default="scope">
                            <el-switch v-model="scope.row.showColumn" />
                        </template>
                    </el-table-column>
                    <el-table-column label="排序" align="center" width="120">
                        <template #default="scope">
                            <el-button size="small" type="primary" :icon="ArrowUpBold" @click="moveUp(scope.$index)"
                                v-if="scope.$index != 0"></el-button>
                            <el-button size="small" type="warning" :icon="ArrowDownBold" @click="moveDown(scope.$index)"
                                v-if="scope.$index != columnData.length - 1"></el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="column-drawer-box-footer">
                <el-button @click="handleCloseChange">关 闭</el-button>
                <el-button type="primary" @click="handleConfirm">保 存</el-button>
            </div>
        </div>
    </el-drawer>
</template>
<script setup>
import { ElMessage } from 'element-plus'
import { ArrowDownBold, ArrowUpBold } from '@element-plus/icons-vue'
import Sortable from 'sortablejs'
const emit = defineEmits(['close', 'confirm'])
const props = defineProps({
    drawer: {
        type: Boolean,
        default: false
    },
    direction: {
        type: String,
        default: 'rtl'
    },
    tableData: {
        type: Array,
        default: () => []
    }
})


const columnData = ref([])//存储列数据
const initColumnData = ref([]) //存储列初始值


// 监听列改变
watch(() => props.tableData, (val) => {
    if (val && val.length > 0) {
        columnData.value = JSON.parse(val)
        initColumnData.value = JSON.parse(val)
    }
}, {
    deep: true,
    immediate: true
})
// 监听弹窗打开
watch(() => props.drawer, (val) => {
    if (val) {
        // getAllLocalStorageKeys()
        setTimeout(() => {
            getTableInstance()
        }, 500)
    }
})

// 获取本地存储的所有key
async function getAllLocalStorageKeys() {
    const keys = [];
    for (let i = 0; i < localStorage.length; i++) {
        keys.push(localStorage.key(i));
    }
    console.log(keys);
}


// 拖拽排序
const elTableRef = ref(null);
const getTableInstance = () => {
    const el = elTableRef.value.$el.querySelector('.el-table__body tbody')
    new Sortable(el, {
        animation: 180,
        delay: 0,
        onEnd: (e) => {
            const targetRow = columnData.value.splice(e.oldIndex, 1)
            columnData.value.splice(e.newIndex, 0, toRaw(targetRow[0]));
            ElMessage({
                message: '拖动排序成功,点击保存后生效',
                type: 'success',
            })
        },
    })
};

// 关闭按钮事件
function handleCloseChange() {
    columnData.value = JSON.parse(JSON.stringify(initColumnData.value))
    emit('close')
}


// 确认按钮事件
function handleConfirm() {
    emit('close')
    emit('confirm', JSON.stringify(toRaw(columnData.value)))
}
// 上移
const moveUp = (index) => {
    if (index > 0) {
        [columnData.value[index - 1], columnData.value[index]] = [columnData.value[index], columnData.value[index - 1]];
    }
    ElMessage({
        message: '上移排序成功,点击保存后生效',
        type: 'success',
    })
};
// 下移
const moveDown = (index) => {
    if (index < columnData.value.length - 1) {
        [columnData.value[index], columnData.value[index + 1]] = [columnData.value[index + 1], columnData.value[index]];
    }
    ElMessage({
        message: '下移排序成功,点击保存后生效',
        type: 'success',
    })
};
</script>

<style lang='scss' scoped>
.column-drawer-box {
    height: 100%;
    display: flex;
    flex-direction: column;

    .column-drawer-box-content {
        flex: 1;
    }

    .column-drawer-box-footer {
        padding: 10px 0 0;
        margin-top: 10px;
        display: flex;
        align-items: center;
        justify-content: flex-end;
    }
}
</style>